package com.wy.OneClient.util;

import com.wy.OneClient.Info;
import com.wy.OneClient.pojo.AddressInfo;
import com.wy.OneClient.pojo.Message;
import org.fusesource.jansi.Ansi;

import javax.rmi.CORBA.Util;
import java.io.*;
import java.net.*;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
    public static void sendMessageServiceImpl(DatagramSocket datagramSocket, Message message) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        new ObjectOutputStream(byteArrayOutputStream).writeObject(message);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(message.getAddressInfo().getTargetAddressIp()), message.getAddressInfo().getTargetPort());
        datagramSocket.send(datagramPacket);
    }

    public static Message receiveMessageServiceImpl(DatagramSocket datagramSocket) throws IOException, ClassNotFoundException {
        byte[] bytes = new byte[1024*48];
        //建立接收端
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
        datagramSocket.receive(datagramPacket);
        byte[] messageBytes = datagramPacket.getData();
        ByteArrayInputStream bis = new ByteArrayInputStream(messageBytes);
        // 创建ObjectInputStream来反序列化对象
        ObjectInputStream ois = new ObjectInputStream(bis);
        Message message = (Message) ois.readObject();
        return message;
    }

    //    得到当前时间
    public static String getCurrentTime() {
        return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    }

    //    写一个关闭资源的工具类。  如果慢慢写的话会有很多的资源
    public static void close() {

    }

    //    接收消息进行打印
    public static void commandPrintRed(String content) {
        CommandWindowColorUtils.printRed(content);
    }

    public static void commandPrintGreen(String content) {
        CommandWindowColorUtils.print(content, Ansi.Color.GREEN);
    }

    public static void helpInfo() {
        System.out.println("获取帮助信息");
    }

    public static void fillInTheBasicInformation(Message message) {
        Scanner scanner = Info.SCANNER;
        Utils.commandPrintGreen("是否全部使用默认值(使用请输入  Y  )");
        String YN = scanner.nextLine();
        if (YN.equals("Y")) {
            return;
        }
        Utils.commandPrintGreen("请输入你的名字: (使用默认输入wy -default)");
        String name = scanner.nextLine();
        if (!name.equals("wy -default")) {
            message.getUser().setName(name);
        }
        while (true) {
            Utils.commandPrintGreen("请输入目标机ip地址和端口(例如：192.168.1.88:8004): (使用默认输入wy -default)");
            String addressAndIp = scanner.nextLine();
            if (!addressAndIp.equals("wy -default")) {
                if (isValidIP(addressAndIp)) {
                    String[] split = addressAndIp.split(":");
                    message.getAddressInfo().setTargetAddressIp(split[0]);
                    message.getAddressInfo().setTargetPort(Integer.parseInt(split[1]));
                    break;
                }
                Utils.commandPrintRed("格式错误！！！！");
            }
        }
        while (true) {
            Utils.commandPrintGreen("请输入本机开启的端口: (使用默认输入wy -default)");
            String localIp = scanner.nextLine();
            try {
                int port = Integer.parseInt(localIp);
                if (port >= 0 && port <= 65535) {
                    try {
                        ServerSocket serverSocket = new ServerSocket(port);
                        serverSocket.close();
                        message.getAddressInfo().setLocalPort(port);
                        break;
                    } catch (IOException e) {
                        Utils.commandPrintRed("端口已经被占用，选择其他端口");
                    }
                } else {
                    Utils.commandPrintRed("端口不存在");
                }
            } catch (Exception e) {
                Utils.commandPrintRed("端口不合法");
            }
        }

        while (true) {
            Utils.commandPrintGreen("请输入默认文件传输文件夹：(使用默认输入wy -default)");
            String fileDir = scanner.nextLine();
            if (fileDir.equals("wy -default")) {
                break;
            }
            File file = new File(fileDir);
//            如果文件不存在
            if (!file.exists()) {
                continue;
            }
//            如果文件存在
//            设置默认存储文件夹

        }
    }

    public static boolean isValidIP(String ipPort) {
        String ipPortPattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\:[0-9]{1,5}$";
        Pattern pattern = Pattern.compile(ipPortPattern);
        Matcher matcher = pattern.matcher(ipPort);
        return matcher.matches();
    }
}
